import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, Input, OnInit } from '@angular/core';
import { UploadFile } from '@shared/apes/upload';
import { InputBoolean, toBoolean, toNumber } from '@shared/apes/core/util/convert';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import {deepClone, getO} from '../../utils/utils';

@Component({
  selector: 'checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CheckboxComponent),
      multi: true,
    },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CheckboxComponent implements OnInit, ControlValueAccessor {

  initItems: any[] = [];
  fileList = [];
  @Input() disabled;
  @Input() items;
  @Input() formControl;
  @Input() showSelectAll : boolean = true;
  onChange: (value: any) => void = () => null;
  onTouched: () => void = () => null;
  allChecked = false;
  indeterminate = false;

  constructor(private cd: ChangeDetectorRef) {
  }

  ngOnInit() {
    this.initItems = deepClone(this.items);
  }

  updateAllChecked(): void {
    this.indeterminate = false;
    let item = deepClone(this.fileList);
    if (this.allChecked) {
      this.fileList = this.fileList.map(item => {
        return {
          ...item,
          checked: true
        };
      });
    } else {
      this.fileList = this.fileList.map(item => {
        return {
          ...item,
          checked: false
        };
      });
      item = [];
    }
    this.setCheck(item);
  }

  setCheck(param){
    this.formControl.patchValue(param);
  }

  afterValue(value){
    this.items.forEach((item)=>{
      item.checked = null;
      for(let i of value){
        if(item.id == i.id){
          item.checked = true;
        }
      }
    });
    if (this.items.every(item => !item.checked)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.items.every(item => item.checked)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }

  }

  writeValue(value: any): void {
    if (typeof value =='string'){
       value = getO(value);
    }
    if (value){
      this.afterValue(value);
      this.fileList =  [...this.items] || [];
      this.cd.markForCheck();
    }else {
      let param = [];
      this.initItems.forEach((item) => {
        if (item['checked']) {
          param.push(item);
        }
      });
      this.formControl.patchValue(param);
      this.fileList = this.initItems;
    }
  }

  registerOnChange(fn: (_: any) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

}
